from machine import RTC
from machine import Timer , I2C ,Pin
import esp
import network
import ntptime 
import machine,utime
rtc = RTC()
# i2c.readfrom(81,16)
#i2c.writeto_mem(81,0,b"\x08\x00\x00\x00")
# da=i2c.readfrom_mem(81,2,1)

def sync_ntp():
    ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间（秒），不设置就是UTC0
    ntptime.host = 'ntp1.aliyun.com'  # 可选，ntp服务器，默认是"pool.ntp.org"
    try:
        nt=ntptime.time()
        tm = utime.gmtime(nt+3600*8+1)
        utime.sleep_ms(500)
        machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
    except:
        return False
        print("ntptime.settime() False")
    else:
        return True

sta_if = network.WLAN(network.STA_IF)
 
#sta_if.connect("<AP_name>", "<password>") # Connect to an AP

def connectWifi(func=None):
    sta_if = network.WLAN(network.STA_IF)
    n=0
    if not sta_if.isconnected():
        sta_if.connect("Network_1", "15368274761")
        while not sta_if.isconnected():
            n=n+1
            if (func==None):
                print("connect...%02d"%(n))
            else:
                func("conn...%02d"%(n))
            utime.sleep(1)
            if(n>=60):
                sta_if.active(False)
                return False

def sync(func=None):
    
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)  
    if connectWifi(func) ==False :
        return False
    n=1
    if func == None: 
        print("SYNC...%02d"%(n))
    else:
        func("sync...%02d  "%(n))
    while not sync_ntp():
        n=n+1
        utime.sleep(1)
        if func == None: 
            print("SYNC...%02d"%(n))
        else:
            func("sync...%02d      "%(n))
        if n>15:
            return False
    t=rtc.datetime()
    utime.sleep_us(1000000-t[7]+10)
    t=rtc.datetime()
    s=((t[6]//10)<<4) | (t[6]%10)
    m=((t[5]//10)<<4) | (t[5]%10)
    h=((t[4]//10)<<4) | (t[4]%10)
    d=((t[2]//10)<<4) | (t[2]%10)
    if t[3] == 6:
        w=0
    else:
        w= t[3]+1
    mo=((t[1]//10)<<4) | (t[1]%10)
    y=(((t[0]-2000)//10)<<4) | (t[0]%10)
    buf=bytes([s,m,h,d,w,mo,y])
    i2c.writeto_mem(81,2,buf)
    sta_if.active(False)  
def settimes(y_,mo_,d_,h_,m_,s_,w):

    s=((s_//10)<<4) | (s_%10)
    m=((m_//10)<<4) | (m_%10)
    h=((h_//10)<<4) | (h_%10)
    d=((d_//10)<<4) | (d_%10)
    mo=((mo_//10)<<4) | (mo_%10)
    y=(((y_-2000)//10)<<4) | (y_%10)
    buf=bytes([s,m,h,d,w,mo,y])
    i2c.writeto_mem(81,2,buf)
def getdatatime():
    da=i2c.readfrom_mem(81,2,7)
    s=((da[0]>>4) * 10) + (da[0]&0x0f)
    m=(((da[1]&0x7f)>>4) * 10) + (da[1]&0x0f)
    h=(((da[2]&0b00111111)>>4) * 10) + (da[2]&0x0f)
    d=(((da[3]&0b00111111)>>4) * 10) + (da[3]&0x0f)
    w=(da[4]&0b00000111)
    mo=(((da[5]&0b00011111)>>4) * 10) + (da[5]&0x0f)
    y=((da[6]>>4) * 10) + (da[6]&0x0f)
    return (y,mo,d,w,h,m,s)
if __name__ == "__main__":
    # i2c = I2C(1,scl=Pin(18), sda=Pin(19),freq=400000)
#     i2c = I2C(0, scl=Pin(5), sda=Pin(10), freq=400000)
    import lc
    i2c = I2C(0,scl=Pin(lc.scl), sda=Pin(lc.sda), freq=400000)
    sync()

    i2c.writeto_mem(81,0x01,bytes([0b00011111]))
    i2c.writeto_mem(81,0x0e,bytes([0b10000010,1]))
    

    while 1 :
        t=rtc.datetime()
        da=i2c.readfrom_mem(81,2,8)
        t=rtc.datetime()
        s=((da[0]>>4) * 10) + (da[0]&0x0f)
        m=((da[1]>>4) * 10) + (da[1]&0x0f)
        h=((da[2]>>4) * 10) + (da[2]&0x0f)
        d=((da[3]>>4) * 10) + (da[3]&0x0f)
        w=((da[4]>>4) * 10) + (da[4]&0x0f)
        mo=((da[5]>>4) * 10) + (da[5]&0x0f)
        y=((da[6]>>4) * 10) + (da[6]&0x0f)

        print("%02d:%02d:%02d"%(h,m,s))
        print("20%02d-%02d-%02d %01d"%(y,mo,d,w))
        # print(da)
        print(t)
        utime.sleep_us(1000000-t[7])